
import datetime
import math
import uuid

from flask import Blueprint, request

from app import get_db_connect
from app.common.auth import check_auth, classSchema
from app.common.responses import re_response


bp_classes = Blueprint("bp_classes", __name__)

# classname不能重复
@bp_classes.route("/addclasses", methods=[ "POST"])
def classes_add():
    if check_auth() > 1:
        print(1)
        return re_response(code=2001,msg="新增失败")
    try:
        classuuid = uuid.uuid1()
        data = request.json
        classname = data["classname"]
        classid = data["classid"]
        create_time = datetime.datetime.now()

        cursor = get_db_connect().cursor()
        count = cursor.execute("select * from classes where classname = '%s'" % classname)
        if count > 0:
            print(2)
            return re_response(code=2001, msg="新增失败")

        f = cursor.execute('INSERT INTO classes (uuid, classname,classid ,create_time) VALUES (%s, %s,%s, %s)',
                           (classuuid, classname ,classid,create_time))
        if f :
            return re_response(msg = "新增成功")
    except Exception as e:
        print(e)
        print(3)
        return re_response(code = 2001 , msg = "新增失败")


@bp_classes.route("/getclasses", methods=["GET"])
def classes_get():
    classname = request.headers.get('classname','null')
    if check_auth() > 1:
        return re_response(code=2001, msg="查询失败")
    try:
        connection = get_db_connect()
        with connection.cursor() as cursor:
            page = int(request.args.get('page', 1))
            pageSize = int(request.args.get('pageSize', 10))
            # 跳过这么多条数据，获取当页数据
            offset = (page - 1) * pageSize
            total = cursor.execute('select * from classes')
            # 总页数
            pages = math.ceil(total / pageSize)
            if not classname:
                count = cursor.execute("SELECT * FROM classes LIMIT %s OFFSET %s" % (pageSize, offset))
                user_data = cursor.fetchall()
            else:
                count = cursor.execute("SELECT * FROM classes where classname like '%s'LIMIT %s OFFSET %s " % ( f"%{classname}%",pageSize, offset))
                user_data = cursor.fetchall()
            schema = classSchema(many=True)
            user_data = schema.dump(user_data)
        connection.close()
        return re_response( msg = "查询成功",data=user_data)
    except Exception as e:
        print(e)
        return re_response(code = 2001 , msg = "查询失败")

@bp_classes.route("/updateclasses", methods=[ "POST"])
def classes_update():
    data = request.json
    # 用classname,
    classname= data['classname']
    if check_auth() :
        return re_response(code=2001, msg="更新失败")
    try:
        cursor = get_db_connect().cursor()
        f = cursor.execute("select * from classes where classname = '%s'" % classname)
        user_data = cursor.fetchall()[0]
        if not f :
            return re_response(code=2001, msg="更新失败")
        newname = data["newname"]

        cursor.execute("update classes  set classname='%s' where classname = '%s'" % (newname,classname))
        return re_response(msg="更新成功")
    except Exception as e:
        print(e)
        return re_response(code=2001, msg="更新失败")


@bp_classes.route("/deleteclasses", methods=[ "POST"])
def classes_delete():

    if check_auth() > 1:
        return re_response(code=2001, msg="删除失败")
    data = request.json
    # classname,不是uuid
    data = eval(data.get('classname'))
    try:
        cursor = get_db_connect().cursor()
        for classname in data:
            f = cursor.execute("select * from classes where classname = '%s'" % classname)
            user_data = cursor.fetchall()
            if not f:
                return re_response(code=2001, msg="删除失败")
        for classname in data:
            cursor.execute("DELETE  from classes where classname='%s'" % classname)
        return re_response(msg="删除成功")
    except Exception as e:
        print(e)
        return re_response(code=2001, msg="删除失败")